package com.szl.sbssh.service.impl;

import com.szl.sbssh.jpa.OrganizationRepository;
import com.szl.sbssh.model.Torganization;
import com.szl.sbssh.pageModel.base.Tree;
import com.szl.sbssh.service.OrganizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Author: songzhonglin
 * Date: 2018/4/18
 * Time: 10:55
 * Description:
 **/
@Service
public class OrganizationServiceImpl implements OrganizationService {

    @Autowired
    OrganizationRepository organizationRepository;

    @Override
    public List<Tree> tree() {

        List<Tree> lt = new ArrayList<Tree>();

        List<Torganization> l = organizationRepository.findAll(new Specification<Torganization>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<Torganization> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                query.orderBy(cb.asc(root.get("seq").as(Integer.class)));
                return query.getRestriction();
            }
        });

        if ((l != null) && (l.size() > 0)) {
            for (Torganization r : l) {
                Tree tree = new Tree();
                tree.setId(r.getId().toString());
                if (r.getOrganization() != null) {
                    tree.setPid(r.getOrganization().getId().toString());
                }
                tree.setText(r.getName());
                tree.setIconCls(r.getIcon());
                lt.add(tree);
            }
        }
        return lt;
    }
}
